package edu.ielab.localansys.ui;

import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.BorderLayout;

import javax.swing.ImageIcon;
import javax.swing.JSplitPane;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.Rectangle;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Vector;

import javax.swing.JList;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;


public class ResultUI extends JPanel {

	private static final long serialVersionUID = 1L;
	private JSplitPane jSplitPane = null;
	private JScrollPane jScrollPane = null;
	private JPanel jPanel = null;
	private JButton jButton = null;
	private JButton jButton1 = null;
	private JButton jButton2 = null;
	private JList jList = null;
	private Vector<String> lFileNameList;
	private String clickedFileNameTemp = null;
	private String DefaultFileBase = "c:/serviceTemp/";  //  @jve:decl-index=0:
	private JTabbedPane jTabbedPane = null;
	private JImagePane jImagePane = null;
	private JScrollPane jScrollPane1 = null;
	private JTextArea jTextArea = null;
	private JScrollPane jScrollPane2 = null;
	private JTextArea jTextArea1 = null;
	/**
	 * This is the default constructor
	 */
	public ResultUI() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(688, 513);
		this.setLayout(new BorderLayout());
		this.add(getJSplitPane(), BorderLayout.CENTER);
		this.add(getJPanel(), BorderLayout.NORTH);
		this.add(getJScrollPane2(), BorderLayout.SOUTH);
	}

	/**
	 * This method initializes jSplitPane	
	 * 	
	 * @return javax.swing.JSplitPane	
	 */
	private JSplitPane getJSplitPane() {
		if (jSplitPane == null) {
			jSplitPane = new JSplitPane();
			jSplitPane.setDividerLocation(150);
			jSplitPane.setRightComponent(getJTabbedPane());
			jSplitPane.setLeftComponent(getJScrollPane());
		}
		return jSplitPane;
	}

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getJList());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			jPanel = new JPanel();
			jPanel.setLayout(null);
			jPanel.setPreferredSize(new Dimension(0, 55));
			jPanel.add(getJButton(), null);
			jPanel.add(getJButton1(), null);
			jPanel.add(getJButton2(), null);
		}
		return jPanel;
	}

	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton() {
		if (jButton == null) {
			jButton = new JButton();
			jButton.setBounds(new Rectangle(91, 13, 111, 33));
			jButton.setText("List Results");
			jButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					listFileListInPanel(); // TODO Auto-generated Event stub actionPerformed()
				}
			});
		}
		return jButton;
	}

	protected void listFileListInPanel() {
			try {
				URL lUrl = new URL(getWebsterURL());
				URLConnection connection = lUrl.openConnection();
				InputStream is=connection.getInputStream();		     
				lFileNameList = inputStream2String(is); 
				is.close();
			    this.getJList().setListData(lFileNameList);
			} catch (Exception e) {
				e.printStackTrace();
				lFileNameList.clear();
			}
	}

	private String getWebsterURL() {
		return "http://192.168.0.101:9000/result";
	}

	/**
	 * This method initializes jButton1	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setBounds(new Rectangle(295, 14, 110, 33));
			jButton1.setText("Show Result");
			jButton1.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					showResultInPanel(); // TODO Auto-generated Event stub actionPerformed()
				}
			});
		}
		return jButton1;
	}

	protected void showResultInPanel() {
		if(clickedFileNameTemp == null)
			return;
		createFolder(DefaultFileBase);
		console("Downloading... " + clickedFileNameTemp);
		downloadFile(getWebsterURL() + "/" + clickedFileNameTemp,new File(DefaultFileBase+clickedFileNameTemp));
		console("Download Complete, file name: " + clickedFileNameTemp);
		if(isPicture(clickedFileNameTemp)) {
			getJTabbedPane().setSelectedIndex(0);
			ImageIcon   ii   =   new   ImageIcon(DefaultFileBase+clickedFileNameTemp);   
			int height = ii.getIconHeight();   
			int width = ii.getIconWidth(); 
			jImagePane.setPreferredSize(new Dimension(width,height));
			jImagePane.setImageDisplayMode(JImagePane.CENTRE);
			jImagePane.setBackgroundImage(getToolkit().getImage(DefaultFileBase+clickedFileNameTemp));
			console("show grah result " + clickedFileNameTemp);
		} else if(isText(clickedFileNameTemp)) {
			getJTabbedPane().setSelectedIndex(1);
			File file = new File(DefaultFileBase+clickedFileNameTemp);
			StringBuffer tempStringBuffer = new StringBuffer();
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new FileReader(file));
				String tempString = null;
			while ((tempString = reader.readLine()) != null){
				tempStringBuffer.append(tempString+"\r\n");
			}
			reader.close();
			} catch (IOException e) {
			e.printStackTrace();
			} finally {
				if (reader != null){
					try {
							reader.close();
					} catch (IOException e1) {
						}
					}
				}		
			console("show text result " + clickedFileNameTemp);
			jTextArea.setText(tempStringBuffer.toString());
		} else {
			console("this kind of file type is not supported");
		}
		
//		int height = ii.getIconHeight();   
//		int width = ii.getIconWidth(); 
//		jImagePane.setPreferredSize(new Dimension(width,height));
//		jImagePane.setImageDisplayMode(JImagePane.CENTRE);
//		jImagePane.setBackgroundImage(getToolkit().getImage(DefaultFileBase+clickedFileNameTemp));
	}

	private void console(String string) {
		this.getJTextArea1().setText(this.getJTextArea1().getText()+System.getProperty("line.separator")+string);
	}

	private boolean isText(String clickedFileNameTemp2) {
		if(clickedFileNameTemp2.toLowerCase().endsWith(".txt") || clickedFileNameTemp2.toLowerCase().endsWith(".mac") || clickedFileNameTemp2.toLowerCase().endsWith(".out"))
			return true;
		return false;
	}

	private boolean isPicture(String clickedFileNameTemp2) {
		if(clickedFileNameTemp2.toLowerCase().endsWith(".jpg") || clickedFileNameTemp2.toLowerCase().endsWith(".png") || clickedFileNameTemp2.toLowerCase().endsWith(".bmp"))
			return true;
		return false;
	}

	/**
	 * This method initializes jButton2	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButton2() {
		if (jButton2 == null) {
			jButton2 = new JButton();
			jButton2.setBounds(new Rectangle(496, 13, 110, 33));
			jButton2.setText("Download");
		}
		return jButton2;
	}

	/**
	 * This method initializes jList	
	 * 	
	 * @return javax.swing.JList	
	 */
	private JList getJList() {
		if (jList == null) {
			jList = new JList();
			jList.setVisibleRowCount(800);
			jList.addMouseListener(new java.awt.event.MouseAdapter() {
				public void mouseClicked(java.awt.event.MouseEvent e) {
					int index = getJList().locationToIndex(e.getPoint());
					String item = (String)getJList().getModel().getElementAt(index);
					clickedFileNameTemp = item;
				}
			});
		}
		return jList;
	}
	
	private Vector<String> inputStream2String(InputStream is) throws IOException{
		Vector fileNameList = new Vector<String>();   
		BufferedReader in = new BufferedReader(new InputStreamReader(is));
		String line = "";
		while ((line = in.readLine()) != null){
			fileNameList.add(getShortFileName(line));
		}		   
		return fileNameList;
	}
	
	private String getShortFileName(String fileName){
		fileName.trim();
		int beginIndex = 0;
		beginIndex = fileName.indexOf("\\");
		while(beginIndex >=0 )
		{
			fileName = fileName.substring(beginIndex+1);
			beginIndex = fileName.indexOf("\\");
		}
		int endIndex = fileName.indexOf("\t");
		fileName = fileName.substring(0, endIndex);
		return fileName;
	}

	private String createFolder(String folderPath) {
        String txt = folderPath;
        try {
            java.io.File myFilePath = new java.io.File(txt);
            txt = folderPath;
            if (!myFilePath.exists()) {
                myFilePath.mkdir();
            }
        }
        catch (Exception e) {
        	System.out.println(e);  
        	
        }
        return txt;
    }
	
	private void downloadFile(String urlDown,File fileOut)
	{
		
		URL url = null;
//		this.getOutMsgTextArea().setText(this.getOutMsgTextArea().getText()+ "\ndownloading..." );
		try {
			
			url = new URL(urlDown);	
			
			URLConnection connection;
			InputStream is;					
			
			connection = url.openConnection();
			is=connection.getInputStream();				
			
			OutputStream os = null ;
			os = new FileOutputStream(fileOut);
			int data = 0;
			while(data >= 0){			
				data = is.read();
				os.write(data);
			}
			
			is.close();
			os.close();
//			this.getOutMsgTextArea().setText(
//					this.getOutMsgTextArea().getText()+ "\ndownload file " + url.toString() + " to " + fileOut.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
//			this.getOutMsgTextArea().setText(this.getOutMsgTextArea().getText()+ "\nfile download error!" );
		}
	}

	/**
	 * This method initializes jTabbedPane	
	 * 	
	 * @return javax.swing.JTabbedPane	
	 */
	private JTabbedPane getJTabbedPane() {
		if (jTabbedPane == null) {
			jTabbedPane = new JTabbedPane();
			jTabbedPane.addTab("Graph Result", null, getJImagePane(), null);
			jTabbedPane.addTab("Text Result", null, getJScrollPane1(), null);
		}
		return jTabbedPane;
	}

	/**
	 * This method initializes jImagePane	
	 * 	
	 * @return edu.ielab.localansys.ui.JImagePane	
	 */
	private JImagePane getJImagePane() {
		if (jImagePane == null) {
			jImagePane = new JImagePane();
		}
		return jImagePane;
	}

	/**
	 * This method initializes jScrollPane1	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane1() {
		if (jScrollPane1 == null) {
			jScrollPane1 = new JScrollPane();
			jScrollPane1.setViewportView(getJTextArea());
		}
		return jScrollPane1;
	}

	/**
	 * This method initializes jTextArea	
	 * 	
	 * @return javax.swing.JTextArea	
	 */
	private JTextArea getJTextArea() {
		if (jTextArea == null) {
			jTextArea = new JTextArea();
		}
		return jTextArea;
	}

	/**
	 * This method initializes jScrollPane2	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane2() {
		if (jScrollPane2 == null) {
			jScrollPane2 = new JScrollPane();
			jScrollPane2.setPreferredSize(new Dimension(3, 100));
			jScrollPane2.setViewportView(getJTextArea1());
		}
		return jScrollPane2;
	}

	/**
	 * This method initializes jTextArea1	
	 * 	
	 * @return javax.swing.JTextArea	
	 */
	private JTextArea getJTextArea1() {
		if (jTextArea1 == null) {
			jTextArea1 = new JTextArea();
		}
		return jTextArea1;
	}
}
